const crypto=require('crypto')
const axios=require('axios')
const {spawnSync}=require('child_process')
const NodeRSA=require('node-rsa')
const app_id='bBobltZIWErP2x8EAyeAQUUb'

class OAController{
    static #test_key(){
        if(global.publicKey!=null&&global.privateKey!=null){
            return global.publicKey,global.privateKey
        }
        const { publicKey, privateKey } = crypto.generateKeyPairSync('rsa', {
            modulusLength: 4096,
            publicKeyEncoding: {
              type: 'spki',
              format: 'pem'
            },
            privateKeyEncoding: {
              type: 'pkcs8',
              format: 'pem'
            }
          })
          global.publicKey=publicKey.replace(/\n/g,'')
          global.privateKey=privateKey.replace(/\n/g,'')
          return global.publicKey, global.privateKey
    }

    static async #test_regist(){
        try{
            const {publicKey,privateKey}=OAController.#test_key()
            const datas=await axios.post('http://119.84.149.47:18001/api/ec/dev/auth/regist',
                {},
                {
                    headers:{
                        "appid":app_id,
                        "cpk":publicKey
                    }
                }
            )
            global.server_public_key=datas.data.spk
            global.server_secret=datas.data.secret
        }catch(err){
            console.error(err)
            throw("获取spk与secret失败")
        }
    }

    static #encrypt(data,spk){
        try{
            const child=spawnSync('java',['-classpath', `${__dirname}/../hutool/hutool.jar`, `${__dirname}/../hutool/encryptBase64.java`, data, spk])
            return child.stdout.toString('utf8')
        }catch(err){
            console.error(err)
        }
        throw("调用java接口加密失败")
    }

    static async #test_get_token(){
        if(global.server_secret==null)
            await OAController.#test_regist()
        if(global.token!=null)
            return global.token
        try{
            const encrypted_secret=OAController.#encrypt(global.server_secret,global.server_public_key)
            const ret=await axios.post('http://119.84.149.47:18001/api/ec/dev/auth/applytoken',
                {},
                {
                    headers:{
                        appid:app_id,
                        secret:encrypted_secret
                    }
                }
            )
            if(ret.data.status==true){
                global.token=ret.data.token
                return global.token
            }
        }catch(err){
            console.error(err)
        }
        throw("获取token失败")
    }

    static async #getHrmsubcompany(){
        try{
            var token=await OAController.#test_get_token()
            var encrypted_userid=OAController.#encrypt('1',global.server_public_key)
            var ret=await axios.post('http://119.84.149.47:18001/api/hrm/resful/getHrmsubcompanyWithPage',
                {
                    params:{
                        created:'2000-01-01',
                        pagesize:1000
                    }
                },
                {
                    headers:{
                        'Content-Type':'application/json',
                        'appid':app_id,
                        'token':token,
                        'userid':encrypted_userid
                    }
                }
            )
            // console.log(JSON.stringify(ret.data,null,2))
            return ret.data.data.dataList
        }catch(err){
            console.error(err)
        }
        throw('获取分部列表失败')
    }

    static async #getHrmdepartment(subcompanyid1){
        try{
            var token=await OAController.#test_get_token()
            var encrypted_userid=OAController.#encrypt('1',global.server_public_key)
            var ret=await axios.post('http://119.84.149.47:18001/api/hrm/resful/getHrmdepartmentWithPage',
                {
                    params:{
                        created:'2000-01-01',
                        subcompanyid1:subcompanyid1,
                        pagesize:1000
                    }
                },
                {
                    headers:{
                        'Content-Type':'application/json',
                        'appid':app_id,
                        'token':token,
                        'userid':encrypted_userid
                    }
                }
            )
            // console.log(JSON.stringify(ret.data,null,2))
            return ret.data.data.dataList
        }catch(err){
            console.error(err)
        }
        throw('获取部门列表失败')
    }

    static async #getHrmUserInfo(subcompanyid1){
        try{
            var token=await OAController.#test_get_token()
            var encrypted_userid=OAController.#encrypt('1',global.server_public_key)
            var ret=await axios.post('http://119.84.149.47:18001/api/hrm/resful/getHrmUserInfoWithPage',
                {
                    params:{
                        created:'2000-01-01',
                        subcompanyid1:subcompanyid1,
                        pagesize:1000
                    }
                },
                {
                    headers:{
                        'Content-Type':'application/json',
                        'appid':app_id,
                        'token':token,
                        'userid':encrypted_userid
                    }
                }
            )
            // console.log(JSON.stringify(ret.data,null,2))
            return ret.data.data.dataList
        }catch(err){
            console.error(err)
        }
        throw('获取人员列表失败')
    }
    
    static #travel_tree(tree,children,supdepid){
        // console.log(`tree.id:${tree.id},supdepid:${supdepid}`)
        if(tree.lastname){
            // console.log(tree.lastname)
            return false
        }
        if(tree.id==supdepid){
            Array.prototype.push.apply(tree.children,children)
            return true
        }
        for(var i=0;i<tree.children.length;i++){
            if(OAController.#travel_tree(tree.children[i],children,supdepid))
                return true
        }
        return false
    }

    // static #travel_tree_2(tree,children,departmentid){
    //     console.log(`tree.id:${tree.id},departmentid:${departmentid}`)
    //     if(tree.id==departmentid){
    //         tree.userlist=children
    //         return true
    //     }
    //     for(var i=0;i<tree.children.length;i++){
    //         if(OAController.#travel_tree_2(tree.children[i],children,departmentid))
    //             return true
    //     }
    //     return false
    // }

    static #make_tree(list, user_list){
        var tree={
            id:'0',
            children:[],
            userlist:[]
        }
        var map={}
        for(var i=0;i<list.length;i++){
            if(!map[list[i].supdepid]) map[list[i].supdepid]=[]
            map[list[i].supdepid].push(list[i])
        }
        while(Object.keys(map).length>0){
            // console.log(Object.keys(map).length)
            for(var i in map){
                var added=OAController.#travel_tree(tree, map[i],i)
                if(added) delete map[i]
            }
        }
        var user_map={}
        for(var i=0;i<user_list.length;i++){
            if(!user_map[user_list[i].departmentid]) user_map[user_list[i].departmentid]=[]
            user_map[user_list[i].departmentid].push(user_list[i])
        }
        while(Object.keys(user_map).length>0){
            // console.log(Object.keys(user_map).length)
            for(var i in user_map){
                var added=OAController.#travel_tree(tree,user_map[i],i)
                if(added) delete user_map[i]
            }
        }
        return tree
    }

    async get_total(req,res){
        if(global.total!=null){
            res.send(200,global.total)
            return
        }
        try{
            var total=[]
            var subcompanylist=await OAController.#getHrmsubcompany()
            for(var i=0;i<subcompanylist.length;i++){
                var company={
                    label:subcompanylist[i].subcompanyname,
                    id:subcompanylist[i].id,
                    canceled:subcompanylist[i].canceled,
                    children:[]
                }
                var departmentlist=await OAController.#getHrmdepartment(company.id)
                var userlist=await OAController.#getHrmUserInfo(company.id)
                var list=[]
                for(var j=0;j<departmentlist.length;j++){
                    var department={
                        label:departmentlist[j].departmentname,
                        subcompanyid1:departmentlist[j].subcompanyid1,
                        supdepid:departmentlist[j].supdepid,
                        id:departmentlist[j].id,
                        canceled:departmentlist[j].canceled,
                        children:[],
                        userlist:[]
                    }
                    list.push(department)
                }
                var user_list=[]
                for(var k=0;k<userlist.length;k++){
                    var user={
                        subcompanyid1:userlist[k].subcompanyid1,
                        subcompanyname:userlist[k].subcompanyname,
                        departmentid:userlist[k].departmentid,
                        departmentname:userlist[k].departmentname,
                        id:userlist[k].id,
                        loginid:userlist[k].loginid,
                        lastname:userlist[k].lastname,
                        policy:userlist[k].policy,
                        bepartydate:userlist[k].bepartydate,
                        telephone:userlist[k].telephone,
                        status:userlist[k].status
                    }
                    user_list.push(user)
                }
                // console.log('make tree')
                var tree=OAController.#make_tree(list,user_list)
                company.children=tree.children
                total.push(company)
            }
            global.total=total
            res.send(200,global.total)
        }catch(err){
            console.error(err)
            res.send(500,'获取分部列表失败')
        }
    }

    async test_key(req,res){
        try{
            var token=await OAController.#test_get_token()
            var encrypted_userid=OAController.#encrypt('1',global.server_public_key)
            // //获取用户信息
            // var ret=await axios.post('http://119.84.149.47:18001/api/hrm/resful/getHrmUserInfoWithPage',
            //     {
            //         params:{
            //             departmentid:'524'
            //         }
            //     },
            //     {
            //         headers:{
            //             'Content-Type':'application/json',
            //             'appid':app_id,
            //             'token':token,
            //             'userid':encrypted_userid
            //         }
            //     }
            // )
            // res.send(200,ret.data)
            // return

            // //获取部门列表
            // var ret=await axios.post('http://119.84.149.47:18001/api/hrm/resful/getHrmdepartmentWithPage',
            //     {
            //         params:{
            //             created:'2000-01-01',
            //             pagesize:1000
            //         }
            //     },
            //     {
            //         headers:{
            //             'Content-Type':'application/json',
            //             'appid':app_id,
            //             'token':token,
            //             'userid':encrypted_userid
            //         }
            //     }
            // )
            // res.send(200,ret.data)
            // return

            // //发送信息
            // var formData=new URLSearchParams()
            // formData.append('code','1151')
            // formData.append('loginIdList','liqiong')
            // formData.append('title','测试asdfdsasdf')
            // formData.append('context','测试context<br>abcabc')
            // formData.append('linkUrl','http://industrybrain-cq.cn')
            // formData.append('linkMobileUrl','http://industrybrain-cq.cn')
            // var ret=await axios.post('http://119.84.149.47:18001/api/ec/dev/message/sendCustomMessageSingle',
            //     formData,
            //     {
            //         headers:{
            //             'Content-Type':'application/x-www-form-urlencoded',
            //             'appid':app_id,
            //             'token':token,
            //             'userid':encrypted_userid
            //         }
            //     }
            // )
            // console.log(ret)
            // res.send(200,ret.data)
        }catch(err){
            console.error(err)
            res.send(500,'失败')
        }
    }
}

module.exports=new OAController()